package com.alibaba.product.service.impl;

import com.alibaba.basic.service.IBaiduAiAuditService;
import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.basic.util.LoginContext;
import com.alibaba.org.domain.Employee;
import com.alibaba.org.mapper.EmployeeMapper;
import com.alibaba.product.domain.Product;
import com.alibaba.product.domain.ProductDetail;
import com.alibaba.product.mapper.ProductDetailMapper;
import com.alibaba.product.mapper.ProductMapper;
import com.alibaba.product.service.IProductService;
import com.alibaba.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    
    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Transactional
    @Override
    public void add(Product product) {
        super.add(product);

        ProductDetail productDetail = product.getProductDetail();
        if (productDetail != null){
            productDetail.setProductId(product.getId());
            productDetailMapper.add(productDetail);
        }
    }

    @Transactional
    @Override
    public void update(Product product) {
        super.update(product);
        ProductDetail productDetail = product.getProductDetail();
        if (productDetail != null){
            productDetail.setProductId(product.getId());
            productDetailMapper.updateProductDetailByProductId(productDetail);
        }
    }

    @Transactional
    @Override
    public void delete(Long id) {
        super.delete(id);
        productDetailMapper.delProductDetailByProductId(id);
    }

    @Override
    public void onsale(Long[] ids, HttpServletRequest request) {
        //获取登录信息对象
        Logininfo logininfo = LoginContext.getLoginUser(request);
        //获取审核人
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        for (Long id : ids) {
            Product product = productMapper.findOne(id);
            //1.上架之前对文本和图片做审核
            Boolean textBoo = baiduAiAuditService.textAudit(product.getName());
            Boolean imaBoo = baiduAiAuditService.imageAudit(product.getResources());
            if (textBoo && imaBoo){
                //审核通过：修改状态 + 添加上架的审核成功日志
                product.setOnsaletime(new Date());
                product.setState(1L);
                productMapper.update(product);
        }
    }
    }

    @Override
    public void offsale(Long[] ids) {
        Date offsaletime = new Date();
        productMapper.offsale(offsaletime,ids);
    }
}
